package com.zqs.grainmall.cart.interceptor;

import com.zqs.common.constant.AuthServerConstant;
import com.zqs.common.constant.CartConstant;
import com.zqs.common.vo.MemberResponseVo;
import com.zqs.grainmall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @program: grain-mall
 * @description: 在执行目标方法之前，判断用户的登陆状态。并封装传递给controller目标请求
 * @author: Mr.Zhang
 * @create: 2020-11-18 22:25
 **/
//自定义拦截器
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();
    /**
     * 目标方法执行之前
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {

        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo memberResponseVo = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberResponseVo!=null)
        {
            //用户登陆
            userInfoTo.setUserId(memberResponseVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0)
        {
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME))
                {
                    userInfoTo.setUserkey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }

        //如果没有临时用户一定分配一个临时用户
        if (StringUtils.isEmpty(userInfoTo))
        {
            String uuid= UUID.randomUUID().toString();
            userInfoTo.setUserkey(uuid);
        }
        //目标方法执行之前
        threadLocal.set(userInfoTo);
        //无论登陆还是未登陆都放行
        return true;
    }

    /**
     * 业务执行之后,分配临时用户让浏览器保存
     *
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
    {
        UserInfoTo userInfoTo = new UserInfoTo();
        //如果没有临时用户一定保存一个临时用户
        if (!userInfoTo.isTempUser())
        {
            //持续的延长临时用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserkey());
            //作用域，在整个grainmall.com下都有效
            cookie.setDomain("grainmall.com");
            //设置cookie的过期时间
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
